import http from 'http';
import app from './server';
import config from 'config';

const port = normalizePort(process.env.PORT || config.get('PORT') || '4001');

app.set('port',port);

const server = http.createServer(app);

server.listen(port);
server.on('error',onError);
server.on('listening',onListening);

function onListening() {
  const addr = server.address();
  console.info(`==> 🌎  Newsfeed is running on port ${addr.port} ✅`);
}


function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }
  var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(`${bind} requires elevated privileges`);
      process.extest(1);
      break;
    case 'EADDRINUSE':
      console.error(`${bind} is already in use`);
      process.extest(1);
      break;
    default:
      throw error;
  }
}

function normalizePort(val) {
  var port = parseInt(val, 10); // 转为10基数的整数
  if (isNaN(port)) { // NaN
    // named pipe
    return val; // 返回原数、不作处理
  }
  if (port >= 0) { // 端口 大于等于 0
    // port number
    return port;
  }
  return false; // 否则返回 false
}
